#!/usr/bin/env bash
#! Encoding UTF-8
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

set -e

GITHUB_URL=https://github.com/openresty/openresty/releases

DOWNLOADER=
if [[ -z "${DOWNLOAD_BASE_PATH}" ]] ; then
    LOCAL_PATH=$(dirname $0)
    TMP_ROOT=${LOCAL_PATH}/tmp
else
    LOCAL_PATH=${DOWNLOAD_BASE_PATH}/nginx
    mkdir -p ${LOCAL_PATH}
    TMP_ROOT=${DOWNLOAD_BASE_PATH}/tmp
fi

info(){
    echo "$(date +'%F %T') [INFO] " "$@"
}
waring(){
    echo "$(date +'%F %T') [WARING] " "$@"
}
fatal(){
    echo "$(date +'%F %T') [ERROR] " "$@"
    exit 1
}

# --- create tempory directory and cleanup when done ---
setup_tmp() {
    TMP_DIR=$(mktemp -p ${TMP_ROOT} -d -t exporter-install.XXXXXXXXXX)
    cleanup() {
        code=$?
        set +e
        trap - EXIT
        rm -rf ${TMP_DIR}
        exit $code
    }
    trap cleanup INT EXIT
}

get_release_version() {
  info "$0 Finding latest release"
  case $DOWNLOADER in
      curl)
          if [[ -n ${PROXY_URL} ]] ; then
              VERSION_PROGRAM=$(curl -x ${PROXY_URL} -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o/dev/null | sed -e 's|.*/||')
          else
              VERSION_PROGRAM=$(curl -w '%{url_effective}' -I -L -s -S ${GITHUB_URL}/latest -o/dev/null | sed -e 's|.*/||')
          fi
          
          ;;
      wget)
          VERSION_PROGRAM=$(wget -SqO /dev/null ${GITHUB_URL}/latest 2>&1 | grep Location | sed -e 's|.*/||')
          ;;
      *)
          fatal "Incorrect downloader executable '$DOWNLOADER'"
          ;;
  esac
}

verify_downloader() {
    # Return failure if it doesn't exist or is no executable
    [ -x "$(which $1)" ] || return 1

    # Set verified executable as our downloader program and return success
    DOWNLOADER=$1
    return 0
}
# --- download from github url ---
download() {
    [ $# -eq 2 ] || fatal 'download needs exactly 2 arguments'

    case $DOWNLOADER in
        curl)
            if [[ -n ${PROXY_URL} ]] ; then
                curl -x ${PROXY_URL} -o $1 -sfL $2
            else
                curl -o $1 -sfL $2
            fi
            ;;
        wget)
            wget -qO $1 $2
            ;;
        *)
            fatal "Incorrect executable '$DOWNLOADER'"
            ;;
    esac

    # Abort if download command failed
    [ $? -eq 0 ] || waring 'Download failed'
}

main(){
    # openresty 下载
    verify_downloader curl \
        || verify_downloader wget \
        || fatal 'Can not find curl or wget for downloading files'
    setup_tmp

    get_release_version
    
    mkdir -p ${LOCAL_PATH}
    HASH_URL=https://openresty.org/download/openresty-${VERSION_PROGRAM#*v}.tar.gz.asc
    download ${TMP_DIR}/openresty-${VERSION_PROGRAM#*v}.tar.gz.asc ${HASH_URL}

    TAR_PACKET=openresty-${VERSION_PROGRAM#*v}
    if [[ -f ${LOCAL_PATH}/${TAR_PACKET}.tar.gz ]] ; then
        fatal "Promgram \"${TAR_PACKET}.tar.gz\" already exists ."
    fi
    
    DOWNLOAD_URL=${GITHUB_URL}/download/${VERSION_PROGRAM}/${TAR_PACKET}.tar.gz
    download ${TMP_DIR}/${TAR_PACKET}.tar.gz ${DOWNLOAD_URL}

    gpg ${TMP_DIR}/openresty-${VERSION_PROGRAM#*v}.tar.gz.asc
    if [ $? != 0 ]; then
      fatal "Download sha256 does not match ${HASH_EXPECTED}, got ${HASH_BIN}"
    fi

    info "Promgram \"${TAR_PACKET}.tar.gz\" download success ."
    cp -f ${TMP_DIR}/${TAR_PACKET}.tar.gz ${LOCAL_PATH}/
    # ====================
}

main
